import { defineStore } from 'pinia'
import { getRecommendVideos, toggleLike, recordView } from '@/api/video'
import { debounce } from '@/utils'

export const useVideoStore = defineStore('video', {
  state: () => ({
    // 推荐视频列表
    recommendVideos: [],
    // 当前播放的视频索引
    currentVideoIndex: 0,
    // 是否正在加载
    loading: false,
    // 是否已加载完毕
    finished: false,
    // 分页信息
    pagination: {
      current: 1,
      size: 10,
      total: 0
    }
  }),

  actions: {
    // 获取推荐视频列表
    async fetchRecommendVideos(refresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          current: refresh ? 1 : this.pagination.current,
          size: this.pagination.size
        }
        
        const response = await getRecommendVideos(params)
        console.log('原始API响应:', response)
        
        const { records, total, current } = response.data
        
        console.log('获取到的视频数据:', records)
        console.log('数据条数:', records?.length || 0)
        
        // 检查每个视频的完整数据结构
        records?.forEach((video, index) => {
          console.log(`视频${index}完整数据:`, video)
          console.log(`视频${index}所有字段:`, Object.keys(video))
          
          // 检查可能的视频URL字段
          const possibleVideoUrlFields = ['videoUrl', 'video_url', 'videoPath', 'video_path', 'url', 'path', 'filePath', 'fileName'];
          const possibleCoverUrlFields = ['coverUrl', 'cover_url', 'coverPath', 'cover_path', 'poster', 'thumbnail'];
          
          console.log(`视频${index}可能的视频URL字段:`);
          possibleVideoUrlFields.forEach(field => {
            if (video[field] !== undefined) {
              console.log(`  ${field}: ${video[field]}`);
            }
          });
          
          console.log(`视频${index}可能的封面URL字段:`);
          possibleCoverUrlFields.forEach(field => {
            if (video[field] !== undefined) {
              console.log(`  ${field}: ${video[field]}`);
            }
          });
        })
        
        // 处理视频数据，如果字段名不匹配则进行转换
        const processedRecords = records?.map(video => {
          const processedVideo = { ...video };
          
          // 如果没有videoUrl字段，尝试其他可能的字段名
          if (!processedVideo.videoUrl) {
            const videoUrlField = ['video_url', 'videoPath', 'video_path', 'url', 'path', 'filePath']
              .find(field => video[field]);
            if (videoUrlField) {
              processedVideo.videoUrl = video[videoUrlField];
              console.log(`使用${videoUrlField}作为videoUrl:`, processedVideo.videoUrl);
            }
          }
          
          // 如果没有coverUrl字段，尝试其他可能的字段名
          if (!processedVideo.coverUrl) {
            const coverUrlField = ['cover_url', 'coverPath', 'cover_path', 'poster', 'thumbnail']
              .find(field => video[field]);
            if (coverUrlField) {
              processedVideo.coverUrl = video[coverUrlField];
              console.log(`使用${coverUrlField}作为coverUrl:`, processedVideo.coverUrl);
            }
          }
          
          // 如果URL是相对路径，转换为完整URL
          if (processedVideo.videoUrl && !processedVideo.videoUrl.startsWith('http')) {
            // 如果已经以/api开头，就直接使用；否则才添加API前缀
            if (!processedVideo.videoUrl.startsWith('/api')) {
              if (processedVideo.videoUrl.startsWith('/')) {
                processedVideo.videoUrl = `http://localhost:8080/api/files${processedVideo.videoUrl}`;
              } else {
                processedVideo.videoUrl = `http://localhost:8080/api/files/video/${processedVideo.videoUrl}`;
              }
            } else {
              // 如果已经以/api开头，只需要添加域名
              processedVideo.videoUrl = `http://localhost:8080${processedVideo.videoUrl}`;
            }
            console.log(`转换后的视频URL:`, processedVideo.videoUrl);
          }
          
          if (processedVideo.coverUrl && !processedVideo.coverUrl.startsWith('http')) {
            if (!processedVideo.coverUrl.startsWith('/api')) {
              if (processedVideo.coverUrl.startsWith('/')) {
                processedVideo.coverUrl = `http://localhost:8080/api/files${processedVideo.coverUrl}`;
              } else {
                processedVideo.coverUrl = `http://localhost:8080/api/files/image/${processedVideo.coverUrl}`;
              }
            } else {
              // 如果已经以/api开头，只需要添加域名
              processedVideo.coverUrl = `http://localhost:8080${processedVideo.coverUrl}`;
            }
            console.log(`转换后的封面URL:`, processedVideo.coverUrl);
          }
          
          return processedVideo;
        }) || [];
        
        console.log('处理后的视频数据:', processedRecords);
        
        if (refresh) {
          this.recommendVideos = processedRecords
          this.currentVideoIndex = 0
        } else {
          this.recommendVideos.push(...processedRecords)
        }
        
        this.pagination.current = current + 1
        this.pagination.total = total
        this.finished = this.recommendVideos.length >= total
        
      } catch (error) {
        console.error('获取推荐视频失败:', error)
        console.error('错误详情:', error.response?.data || error.message)
      } finally {
        this.loading = false
      }
    },

    // 点赞视频
    async likeVideo(videoIndex) {
      const video = this.recommendVideos[videoIndex]
      if (!video) return
      
      // 防抖处理
      if (!this.debouncedLike) {
        this.debouncedLike = debounce(async (videoId, index) => {
          try {
            await toggleLike(videoId)
            
            // 更新本地状态
            const targetVideo = this.recommendVideos[index]
            if (targetVideo) {
              targetVideo.isLiked = !targetVideo.isLiked
              if (targetVideo.isLiked) {
                targetVideo.likeCount++
              } else {
                targetVideo.likeCount--
              }
            }
          } catch (error) {
            console.error('点赞失败:', error)
          }
        }, 300)
      }
      
      this.debouncedLike(video.id, videoIndex)
    },

    // 记录视频观看
    async viewVideo(videoId) {
      try {
        await recordView(videoId)
      } catch (error) {
        console.error('记录观看失败:', error)
      }
    },

    // 切换到上一个视频
    toPreviousVideo() {
      if (this.currentVideoIndex > 0) {
        this.currentVideoIndex--
        return this.getCurrentVideo
      }
      return null
    },

    // 切换到下一个视频
    async toNextVideo() {
      if (this.currentVideoIndex < this.recommendVideos.length - 1) {
        this.currentVideoIndex++
      } else {
        // 如果是最后一个视频，尝试加载更多
        if (!this.finished) {
          await this.fetchRecommendVideos()
          if (this.currentVideoIndex < this.recommendVideos.length - 1) {
            this.currentVideoIndex++
          }
        }
      }
      return this.getCurrentVideo
    },

    // 设置当前视频索引
    setCurrentVideoIndex(index) {
      if (index >= 0 && index < this.recommendVideos.length) {
        this.currentVideoIndex = index
        return this.getCurrentVideo
      }
      return null
    },

    // 重置状态
    resetState() {
      this.recommendVideos = []
      this.currentVideoIndex = 0
      this.loading = false
      this.finished = false
      this.pagination = {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },

  getters: {
    // 获取当前视频
    getCurrentVideo: (state) => {
      return state.recommendVideos[state.currentVideoIndex] || null
    },

    // 获取上一个视频
    getPreviousVideo: (state) => {
      const index = state.currentVideoIndex - 1
      return index >= 0 ? state.recommendVideos[index] : null
    },

    // 获取下一个视频
    getNextVideo: (state) => {
      const index = state.currentVideoIndex + 1
      return index < state.recommendVideos.length ? state.recommendVideos[index] : null
    },

    // 是否有更多视频
    hasMore: (state) => {
      return !state.finished && state.recommendVideos.length > 0
    }
  }
}) 